package com.hepinghospital.user.ui.fragment;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.base.BaseLoadsirFragment;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.activity.consult.ChatActivity;
import com.hepinghospital.user.ui.activity.consult.DiagnoseOrderDetailActivity;
import com.hepinghospital.user.ui.widget.EmptyCallback;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.CloudResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.UIConstants;

/**
 * Created by HP on 2020/2/25.
 */

public class CloudListFragment extends BaseLoadsirFragment {

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private String type = "";
    MyAdapter adapter;
    List<CloudResponse> list = new ArrayList<>();

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_cloud_list;
    }

    @Override
    protected void initView() {

        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        if (recyclerView.getItemDecorationCount() == 0) {
            recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                    super.onDraw(c, parent, state);
                }

                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.bottom = DpUtil.dip2px(mContext, 10);
                }
            });
        }

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> getCloudList(type));
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {

        });
    }

    @Override
    protected void initData() {
        type = getArguments().getString("type","0");
        getCloudList(type);

//        getAllOrderList(type);
    }

    @Override
    protected void onNetReload(View v) {
        getCloudList(type);
    }

    @Override
    public void onResume() {
//        getCloudList(type);
        super.onResume();
    }

    public static CloudListFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString("type", type);
        CloudListFragment fragment = new CloudListFragment();
        fragment.setArguments(args);
        return fragment;
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(getActivity()).inflate(R.layout.item_my_ask, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                if (list.get(position).orderStatus == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cloudObj", list.get(position));
                    bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_2);
                    startActivity(PayActivity.class, bundle);
                } else if (list.get(position).orderStatus == 2) {
                    if (list.get(position).readyFlag == 1) {
                        //已经报道
                        Bundle bundle = new Bundle();
                        bundle.putString("diagnoseId", list.get(position).diagnoseId);
                        startActivity(ChatActivity.class, bundle);
                    }

                } else if (list.get(position).orderStatus == 3 || list.get(position).orderStatus == 8) {
                    Bundle bundle = new Bundle();
                    bundle.putString("diagnoseId", list.get(position).diagnoseId);
                    startActivity(ChatActivity.class, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("diagnoseId", list.get(position).diagnoseId);
                    startActivity(DiagnoseOrderDetailActivity.class, bundle);
                }
            });
            holder.tv_department.setText(list.get(position).deptName);
            holder.tv_status.setText(getStatus(list.get(position).orderStatus, list.get(position).readyFlag));
            holder.tv_time.setText("预约时间:" + list.get(position).scheduleDate + " " + list.get(position).scheduleTime);
//            holder.tv_detail.setText(list.get(position).fee);
//            holder.btn_confirm.setText(list.get(position).num);
            holder.tv_name.setText(list.get(position).doctorName);
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, list.get(position).url, holder.img_head);
            holder.btn_confirm.setVisibility(View.VISIBLE);
            holder.tv_detail.setVisibility(View.VISIBLE);
            holder.btn_confirm2.setVisibility(View.GONE);
            if (list.get(position).orderStatus == 3) {
                holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.btn_confirm.setText("进行中");
                holder.tv_detail.setText("您的远程门诊已开始，点击进入");
            } else if (list.get(position).orderStatus == 8) {
                holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.btn_confirm.setText("已开方");
                holder.tv_detail.setText("您的远程门诊已开方，点击进入");
            } else if (list.get(position).orderStatus == 2) {
                if (list.get(position).canSignIn) {
                    holder.btn_confirm.setBackgroundResource(R.drawable.selector_button);
                    holder.btn_confirm.setTextColor(getResources().getColor(R.color.white));
                    holder.btn_confirm.setText("报道");
                    holder.tv_detail.setText("请提前20分钟报道");
                } else {
                    holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                    holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                    holder.btn_confirm.setText("届时请来报道");
                    holder.tv_detail.setText("请提前20分钟报道");
                }
            } else if (list.get(position).orderStatus == 1) {
                holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.btn_confirm.setText("支付");
                holder.tv_detail.setText("请在" + Integer.parseInt(list.get(position).remainPayTime) / 60 + "分钟内支付");
                holder.btn_confirm2.setVisibility(View.VISIBLE);
            } else if (list.get(position).orderStatus == 5 || list.get(position).orderStatus == 4) {
                holder.btn_confirm.setVisibility(View.GONE);
                holder.tv_detail.setVisibility(View.GONE);
            } else if (list.get(position).orderStatus == 7) {
                holder.btn_confirm.setVisibility(View.GONE);
                holder.tv_detail.setVisibility(View.GONE);
            } else if (list.get(position).orderStatus == 10) {
                holder.btn_confirm.setVisibility(View.GONE);
                holder.tv_detail.setVisibility(View.GONE);
            }
            if (list.get(position).readyFlag == 1) {
                holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.btn_confirm.setText("已报道");
                holder.tv_detail.setText("您前面还有" + list.get(position).queueNum + "人正在排队，预计还要" + list.get(position).remainTime + "分钟");
            }


            if (list.get(position).canRefund == 1) {
                holder.btn_refund.setVisibility(View.VISIBLE);
            } else {
                holder.btn_refund.setVisibility(View.GONE);
            }

            holder.btn_refund.setOnClickListener(v -> refund(list.get(position).orderNumber));

            holder.btn_confirm.setOnClickListener(v -> {
                if (list.get(position).orderStatus == 2) {
                    if (list.get(position).canSignIn) {
                        setCloudReady(list.get(position).diagnoseId);
                    }
                } else if (list.get(position).orderStatus == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cloudObj", list.get(position));
                    bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_2);
                    startActivity(PayActivity.class, bundle);
                }
            });
            holder.btn_confirm2.setOnClickListener(v -> cancelOrder(list.get(position).orderId));
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_department, tv_status, tv_time, tv_detail, btn_confirm, btn_confirm2, btn_refund;
            ImageView img_head;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_status = itemView.findViewById(R.id.tv_status);
                tv_department = itemView.findViewById(R.id.tv_department);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_detail = itemView.findViewById(R.id.tv_detail);
                btn_confirm = itemView.findViewById(R.id.btn_confirm);
                btn_confirm2 = itemView.findViewById(R.id.btn_confirm2);
                img_head = itemView.findViewById(R.id.img_head);
                btn_refund = itemView.findViewById(R.id.btn_refund);
            }
        }
    }


    private void getCloudList(String orderStatus) {
        RestProxy.getInstance().getCloudList(BaseApplication.currentUserId, orderStatus, new Observer<List<CloudResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<CloudResponse> cloudResponses) {
                list.clear();
                list.addAll(cloudResponses);
                adapter.notifyDataSetChanged();
                if (cloudResponses.isEmpty()) {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                } else {
                    mBaseLoadService.showSuccess();
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    private String getStatus(int status, int readyFlag) {
        switch (status) {
            case 1:
                return "待支付";
            case 2:
                if (readyFlag == 1) {
                    return "已报道";
                } else {
                    return "未报道";
                }

            case 3:
                return "进行中";
            case 4:
                return "待评价";
            case 5:
                return "已取消";
            case 7:
                return "已完成";
            case 10:
                return "退款中";
            default:
                return "";
        }
    }

    private void refund(String orderNumber) {
        RestProxy.getInstance().refund(orderNumber, new BaseObserver<String>() {
            @Override
            public void onSuccess(String s) {
                getCloudList(type);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }
        });
    }

    private void setCloudReady(String id) {
        RestProxy.getInstance().setCloudReady(BaseApplication.currentUserId, id, "1", new BaseObserver<String>() {
            @Override
            public void onSuccess(String baseResponse) {
                getCloudList(type);
                refreshLayout.finishRefresh(true);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }
        });
    }

    private void cancelOrder(String orderId) {
        RestProxy.getInstance().cancelOrder(orderId, new BaseObserver<String>() {
            @Override
            public void onSuccess(String baseResponse) {
                getCloudList(type);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }
        });
    }
}
